package org.vergil.utils;

import org.vergil.dto.Jwt;
import org.vergil.dto.Playload;
import org.vergil.dto.User;

import java.time.LocalDateTime;

/**
 * Created by vergil on 4/30/17.
 */
public class JwtUtils {

    public static Jwt decodeJwt(String jwtContext) {
        if ("".equals(jwtContext) && null == jwtContext) {
            return null;
        }
        String[] jwts = jwtContext.split("\\.");
        Jwt jwt = new Jwt();
        String header = Encrypt.base64Decode(jwts[0]);
        jwt.setHeader(header);
        String playloadStr = Encrypt.base64Decode(jwts[1]);
        Playload playload = JsonUtils.JsonToBean(playloadStr, Playload.class);
        jwt.setPlayload(playload);
        String signature = jwts[2];
        jwt.setSignature(signature);
        jwt.setJwtContext(jwtContext);
        return jwt;
    }

    public static String EncodeJwt(User user) {
        String header = Encrypt.base64Encode("{\"type\":\"JWT\",\"alg\":\"SHA256\"}");
        Playload playload = new Playload();
        playload.setAub("vergil");
        playload.setSub(user.getUsername());
        playload.setAub(user.getId().toString());
        playload.setIat(LocalDateTime.now().toString());
        playload.setExp(LocalDateTime.now().plusMinutes(30).toString());
        String playloadJson = JsonUtils.ObjectToJson(playload);
        String playloadBase64 = Encrypt.base64Encode(playloadJson);
        String signature = Encrypt.SHA256(header + "." + playload);
        String result = header + "." + playloadBase64 + "." + signature;
        return result;
    }
}
